package com.zhanghe.im.handler;

import com.zhanghe.im.request.JoinGroupRequestPacket;
import com.zhanghe.im.response.JoinGroupResponsePacket;
import com.zhanghe.im.util.SessionUtil;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.group.ChannelGroup;

import java.util.Date;

public class SimpleJoinGroupRequestHandler extends SimpleChannelInboundHandler<JoinGroupRequestPacket> {

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, JoinGroupRequestPacket msg) throws Exception {
        String groupId = msg.getGroupId();
        System.out.println("用户["+SessionUtil.getSession(ctx.channel()).getUserName()+"],申请加入群:"+groupId);
        ChannelGroup channelGroup = SessionUtil.getChannelGroup(groupId);
        JoinGroupResponsePacket joinGroupResponsePacket = new JoinGroupResponsePacket();
        if(channelGroup!=null){
            channelGroup.add(ctx.channel());
            joinGroupResponsePacket.setGroupId(groupId);
            joinGroupResponsePacket.setSuccess(true);
            System.out.println("用户["+SessionUtil.getSession(ctx.channel()).getUserName()+"],加入群:"+groupId);
        }else{
            joinGroupResponsePacket.setSuccess(false);
        }
        ctx.channel().writeAndFlush(joinGroupResponsePacket);
    }
}
